package com.ruoyi.web.qrcodeUtils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.ruoyi.web.qrcodeUtils.vo.QRVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class QRCodeGenerator {
    @Value("${spring.skuQR}")
    private  String path;


    public List<String> bactha(List<QRVo> qrVoList) {
        List<String> list = new ArrayList<>();
        for (QRVo qrVo : qrVoList) {
            String filePath = generateQRCode(qrVo.getSku(), qrVo.getName());
            filePath = filePath.substring(filePath.indexOf("/"));
            list.add(filePath);
        }
        return list;
    }

    public String generateQRCode(String sku, String productName) {
        int width = 180;
        int height = 100;
        String filePath =path +"/photo/"+ sku + "_" + productName + ".png";
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        try {
            //扫码类容
            BitMatrix bitMatrix = new MultiFormatWriter().encode(sku, BarcodeFormat.QR_CODE, width, height, hints);
            // 创建一个带有绘图上下文的BufferedImage
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            // 绘制二维码
            Graphics2D graphics = image.createGraphics();
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, width, height);
            graphics.setColor(Color.BLACK);
            int x_displacement = 50;
            int y_displacement = 10;
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    if (bitMatrix.get(x, y)) {
                        graphics.fillRect(x + x_displacement, y + y_displacement, 1, 1);
                    }
                }
            }

            // 绘制sku
            Font font1 = new Font("宋体", Font.BOLD, 12);
            graphics.setFont(font1);
            graphics.setColor(Color.black);
            graphics.drawString(sku, width / 4 + 10, 15);

            // 绘制商品名称
            // 指定绘制位置
            int x = 2;
            int y = height / 4;
            // 定义每行文本的最大宽度
            int maxWidth = 100;
            Font font2 = new Font("宋体", Font.BOLD, 12);
            graphics.setFont(font2);
            graphics.setColor(Color.black);
            FontMetrics fm = graphics.getFontMetrics();
            int lineHeight = fm.getHeight();

            StringBuilder sb = new StringBuilder();
            int lineWidth = 0;
            int curX = x;
            int curY = y + lineHeight;

            for (char c : productName.toCharArray()) {
                String charAsString = String.valueOf(c);
                int charWidth = fm.stringWidth(charAsString);

                if (lineWidth + charWidth <= maxWidth) {
                    sb.append(charAsString);
                    lineWidth += charWidth;
                } else {
                    System.out.println("ffe:"+sb.toString());
                    graphics.drawString(sb.toString(), curX, curY);
                    sb = new StringBuilder(charAsString);
                    curY += lineHeight;
                    lineWidth = charWidth;
                }
            }
            System.out.println("fff:"+sb.toString());
            graphics.drawString(sb.toString(), curX, curY);

            // 创建 Path 对象
            Path pathIsExists = Paths.get(path +"/photo/");
            // 判断文件夹是否存在
            if (!Files.exists(pathIsExists)) {
                // 如果不存在，创建文件夹
                Files.createDirectories(pathIsExists);
            }
            Path filePathCreate = FileSystems.getDefault().getPath(filePath);
            ImageIO.write(image, "png", filePathCreate.toFile());
            graphics.dispose();
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }


    public ResponseEntity<FileSystemResource> downloadQRCode(String[] imagePaths, HttpServletResponse response) throws IOException {
        // 创建一个临时zip文件
        File zipFile = File.createTempFile("images", ".zip");
        // 使用ZipOutputStream将图片打包成zip文件
        try (FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zipOut = new ZipOutputStream(fos)) {
            for (String imagePath : imagePaths) {
                File imageFile = new File(imagePath);
                if (imageFile.exists()) {
                    try (FileInputStream fis = new FileInputStream(imageFile)) {
                        zipOut.putNextEntry(new ZipEntry(imageFile.getName()));
                        byte[] bytes = new byte[1024];
                        int length;
                        while ((length = fis.read(bytes)) >= 0) {
                            zipOut.write(bytes, 0, length);
                        }
                    }
                }
            }
        }
        // 构建响应体
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/zip"));
        headers.setContentDispositionFormData("attachment", zipFile.getName());
        headers.setContentLength(zipFile.length());

        return new ResponseEntity<>(new FileSystemResource(zipFile), headers, HttpStatus.OK);
    }
}


//HttpHeaders headers = new HttpHeaders();

//            headers.setContentType(MediaType.parseMediaType("application/zip"));
//        headers.setContentDispositionFormData("attachment", "images.zip");
//            headers.setCacheControl("no-cache, no-store, must-revalidate");
//            headers.setPragma("no-cache");
//            headers.setExpires(0);